<template>
  <!-- 商户 -->
  <div class="merchant-page" :scroll-top="scrollTop" :style="{ height: '100vh' }">

    <!-- 固定在顶部的UI -->
    <div class="fixed-header" v-if="showFixedHeader" :style="{ height: capsuleTop + 40 + 'px' }">
      <div class="fixed-header-content">
        <div class="fixed-back-btn" @click="goBack">返回</div>
        <div class="fixed-title">{{ shopInfo.shopName }}</div>

      </div>
    </div>

    <div class="home-page-capsule h-200rpx " :style="{ height: capsuleHeight + 'px', top: capsuleTop + 'px' }"
      @click="goBack">
      <!-- 你的胶囊按钮内容 -->
      返回
    </div>
    <div class="home-page-banner">
      <img
        :src="shopInfo?.shopExtendsJson?.bannerInfo ? shopInfo?.shopExtendsJson?.bannerInfo : '../static/imgs/banner.png'"
        alt="">
    </div>
    <div class="merchant-logo">
      <img class="logo-img" :src="shopInfo.logo" alt="">
      <div class="merchant-logo-title">
        <div>{{ shopInfo.shopName }}</div>
        <!-- <div>月销{{ shopInfo.sales }}+</div> -->
      </div>
      <img class="star-img"
        :src="isCollected ? '../static/imgs/Merchant/yishoucang.png' : '../static/imgs/Merchant/weishoucang.png'" alt=""
        @click="toggleCollect">
    </div>
    <div class="merchant-classification">
      <div class="merchant-classification-header">
        <div class="header-item" :class="{ active: activeTab === 'order' }" @click="switchTab('order')">点餐</div>
        <div class="header-item" :class="{ active: activeTab === 'merchant' }" @click="switchTab('merchant')">商家</div>
        <div class="search-container">
          <div class="search-icon">
            <img src="../static/imgs/Merchant/sousuo2.png" alt="搜索" class="search-icon">
          </div>
          <input v-model="searchValue" type="text" placeholder="商品搜索" class="search-input" @input="handleChange"
            @blur="handleSearchBlur" />
        </div>
      </div>
      <!-- 在 merchant-classification-content 中添加吸附标题层 -->
      <div class="merchant-classification-content" v-if="activeTab === 'order'">

        <!-- 保持原有的左侧分类栏不变 -->
        <div class="content-left" style="height: 1200rpx; overflow-y: auto;box-sizing: border-box;"
          :style="{ paddingBottom: cartItems.length > 0 ? '200rpx' : '40rpx' }">
          <template v-for="(category, index) in categories" :key="index">
            <div class="content-left-item" :class="{ active: activeCategory === index }"
              @click="switchCategory(category, index)">
              <img :src="category.icon" alt="">
              <div>{{ category.categoryName }}</div>
            </div>
          </template>
        </div>
        <scroll-view class="content-right" scroll-with-animation :scroll-into-view="scrollIntoViewId"
          :scroll-into-view-offset="-50" style="height: 1200rpx;" scroll-y :scroll-top="scrollTop"
          @scroll="handleShopScroll">
          <view class="section" v-for="(category, categoryIndex) in CommodityList" :key="categoryIndex"
            :id="'section-' + categoryIndex" :class="{ 'last-section': categoryIndex === CommodityList.length - 1 }">
            <!-- 调整锚点位置，让它刚好在分类标题上方合适的位置 -->
            <div class="item-title sticky-header" :id="`title-${categoryIndex}`">
              <div>{{ category.title }} <span v-if="false">{{ category.sales || 0 }}+</span></div>
            </div>
            <view :id="`category-anchor-${categoryIndex}`" style="height: 1px; margin-bottom: 0rpx;"></view>
            <div class="content-right-item" :id="`category-section-${categoryIndex}`">

              <div class="item-content">
                <template v-if="category.list && category.list.length > 0">
                  <template v-for="(product, productIndex) in category.list" :key="productIndex">
                    <div class="item-content-item" @click.stop="handleProductClick(product)">
                      <img :src="product.thumbnail" alt="">
                      <div class="item-content-item-title">
                        <div class="one">{{ product.goodsName }}</div>
                        <!-- <div class="two">月销 {{ product.monthlySales }}</div> -->
                        <!-- <div class="three">近期购买人数 {{ product.recentBuyers }}</div> -->
                        <div class="four" style="margin-top: 10rpx;">
                          <div class="four-left">
                            <span>￥</span>
                            <span>{{ product.listGoodsSkus?.[0]?.priceStr || product.listGoodsSkus?.[0]?.marketPrice ||
                              0 }}</span>
                          </div>
                          <div class="four-right">
                            <!-- 有规格的商品：显示起售按钮 -->
                            <div v-if="hasSpecifications(product)" class="four-right-copyof"
                              @click.stop="showSpecification(product)">
                              选规格
                            </div>

                            <!-- 无规格的商品：显示加减数量控件 -->
                            <div v-else class="quantity-controls">
                              <img v-if="getProductQuantity(product) > 0" class="quantity-btn"
                                style="margin-right: 0px;" src="../static/imgs/jianhao.png" alt=""
                                @click.stop="decreaseProductQuantity(product)">
                              <div v-if="getProductQuantity(product) > 0" class="quantity-text">{{
                                getProductQuantity(product) }}</div>
                              <img class="quantity-btn" style="margin-right: 0px;"
                                src="../static/imgs/Merchant/tianjia2.png" alt=""
                                @click.stop="increaseProductQuantity(product)">
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                </template>
                <template v-else>
                  <div class="item-content-item-wu">
                    <img src="../static/imgs/zanwu.png" alt="">
                    <div class="text">暂无商品</div>
                  </div>
                </template>
                <template v-if="categoryIndex === CommodityList.length - 1">
                  <div class="item-content-item-wu">
                    <div class="text">已经到底啦!</div>
                  </div>
                </template>
              </div>
            </div>
          </view>
        </scroll-view>

      </div>
      <div class="merchant-classification-content" v-else>
        <!-- 商家信息内容 -->
        <div style="padding: 40rpx; text-align: center; color: #999;">
          {{ shopInfo.remark }}
        </div>
      </div>
    </div>

    <!-- 购物车 -->
    <div class="Shopping-cart" v-if="cartItems.length > 0">
      <div class="Shopping-cart-box" @click="toggleCart">
        <div class="Shopping-cart-box-img">
          <img src="../static/imgs/goumai.png" alt="">
          <div class="Shopping-cart-box-img-text">{{ totalQuantity }}</div>
        </div>
        <div class="Shopping-cart-box-text">
          <div class="Shopping-cart-box-text-top">￥ <span>{{ totalPrice }}</span></div>
          <div class="Shopping-cart-box-text-bottom">预估配送费¥{{ shopInfo.deliveryFeeStr || 0 }}</div>
          <!-- 添加起送价提示 -->
          <!-- <div v-if="shopInfo.startFeeStr && shopInfo.startFeeStr > 0" class="start-fee-tip">
            起送价¥{{ shopInfo.startFeeStr }}
          </div> -->
        </div>
        <div class="Shopping-cart-box-botton" :class="{ 'active': canCheckout }" @click.stop="checkout">
          {{ startFeeText }}
        </div>
      </div>
    </div>

    <wd-overlay :show="showCart" @click.stop="showCart = false" :zIndex="10">
      <view class="Shopping-cart-wrapper">
        <div class="wrapper-box">
          <div class="wrapper-box-header">
            <div class="wrapper-box-header-left">
              已选商品
            </div>
            <div class="wrapper-box-header-right" @click.stop="clearCart">
              清空
            </div>
          </div>
          <div class="wrapper-box-content">
            <div class="item-content">
              <template v-for="(item, index) in cartItems" :key="index">
                <div class="item-content-item">
                  <img :src="item.thumbnail" alt="">
                  <div class="item-content-item-title">
                    <div class="one">{{ item.goodsName }}</div>
                    <div class="two">
                      <template v-for="(spec, specIndex) in item.specDetails" :key="specIndex">
                        <span>{{ spec.specsName }} <span v-if="Number(spec.specsPrice) > 0" style="color: red;">+￥{{
                            spec.specsPrice }}</span></span>
                      </template>
                      <!-- {{ item.specifications.join('，') }} -->
                    </div>
                    <div class="four">
                      <div class="four-left">
                        <span>￥</span>
                        <span>{{
                          (parseFloat(item.listGoodsSkus?.[0]?.priceStr || 0) +
                            parseFloat(item.listGoodsSkus?.[0]?.packPriceStr || 0) +
                            parseFloat(item.specAdditionalPrice || 0)).toFixed(2)
                        }}</span>
                        <span v-if="Number(item.listGoodsSkus?.[0]?.packPriceStr) > 0"
                          style="font-size: 20rpx; margin-left: 8rpx;">+打包费¥{{ item.listGoodsSkus?.[0]?.packPriceStr
                          }}</span>
                      </div>
                      <div class="four-right">
                        <img class="img-left" src="../static/imgs/jianhao.png" alt=""
                          @click.stop="decreaseQuantity(index)">
                        <div>{{ item.quantity }}</div>
                        <img class="img-right" src="../static/imgs/Merchant/tianjia2.png" alt=""
                          @click.stop="increaseQuantity(index)">
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>
      </view>
    </wd-overlay>
    <!-- 规格选择弹窗 -->
    <div class="Specification-box" v-if="isShowSpecification">
      <div class="Specification-bj" @click.stop="closeSpecification"> </div>
      <div class="popup-Specification">
        <div class="popup-Specification-header">
          选规格
        </div>
        <div class="Specification-content">
          <template v-for="(spec, specIndex) in currentProduct.specifications" :key="specIndex">
            <div class="Specification-content-item">
              <div class="Specification-content-item-title">{{ spec.name }}</div>
              <div class="Specification-content-item-content">
                <template v-for="(option, optionIndex) in spec.list" :key="optionIndex">
                  <div :class="{ active: selectedSpecs[spec.name] === option.name }"
                    @click.stop="selectSpec(spec.name, option)">
                    {{ option.name }} <span v-if="Number(option.priceStr) > 0" style="color: red;">+￥{{ option.priceStr
                      }}</span>
                  </div>
                </template>
              </div>
            </div>
          </template>
        </div>
        <div class="Specification-footer">
          <div class="Specification-footer-header">
            <div>已选规格：{{ selectedSpecText }}</div>
          </div>
          <div class="Specification-footer-bottom">
            <div class="left">
              <span>￥</span>{{ currentProduct.priceStr }}
            </div>
            <div class="right" @click.stop="addToCart">加入购物车</div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import bottomNav from '@/components/bottomNav.vue'

const capsuleHeight = ref(0)
const capsuleTop = ref(0)
const isSearchFixed = ref(false)
const value = ref('')
const scrollTop = ref(0)
const searchInputRef = ref(null)
const isShowSpecification = ref(false)
const showCart = ref(false)
const isCollected = ref(false)
const activeTab = ref('order')
const activeCategory = ref(0)
const currentProduct = ref({})
const selectedSpecs = ref({})
const cartItems = ref([])
const showFixedHeader = ref(false)

// 分类数据
const categories = ref([])
const sourceCategories = ref([])

// 计算属性
const totalQuantity = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

const totalPrice = computed(() => {
  const subtotal = cartItems.value.reduce((total, item) => {
    const priceStr = parseFloat(item.listGoodsSkus?.[0]?.priceStr) || 0;  // 保证为数字，若为非数字则默认为0
    const packPriceStr = parseFloat(item.listGoodsSkus?.[0]?.packPriceStr) || 0;   // 获取打包费，转换为数字，如果无效则默认为0
    const specAdditionalPrice = parseFloat(item.specAdditionalPrice) || 0; // 加上规格额外价格
    const quantity = parseInt(item.quantity, 10) || 0;  // 确保数量是数字，若不是则默认为0
    return total + ((priceStr + packPriceStr + specAdditionalPrice) * quantity);
  }, 0);

  // const deliveryFeeStr = parseFloat(shopInfo.value.deliveryFeeStr) || 0;  // 确保配送费是数字，若无效则为0
  const total = subtotal;

  return total.toFixed(2);  // 最终结果保留2位小数
});

const canCheckout = computed(() => {
  const subtotal = cartItems.value.reduce((total, item) => {
    const priceStr = parseFloat(item.listGoodsSkus?.[0]?.priceStr) || 0;  // 保证为数字，若为非数字则默认为0
    const packPriceStr = parseFloat(item.listGoodsSkus?.[0]?.packPriceStr) || 0;  // 同上
    const specAdditionalPrice = parseFloat(item.specAdditionalPrice) || 0; // 加上规格额外价格
    const quantity = parseInt(item.quantity, 10) || 0;  // 确保数量是数字，若不是则默认为0
    return total + ((priceStr + packPriceStr + specAdditionalPrice) * quantity);
  }, 0);
  // 获取起送价，如果没有则默认为0
  const startFeeStr = parseFloat(shopInfo.value.startFeeStr) || 0;
  // 获取配送费
  // const deliveryFeeStr = parseFloat(shopInfo.value.deliveryFeeStr) || 0;
  // 计算总金额（商品小计 + 配送费）
  const totalAmount = subtotal;
  // 只有总金额（含配送费）超过起送价才能结算
  return totalAmount >= startFeeStr;
})

// 获取起送价显示文本
const startFeeText = computed(() => {
  const startFeeStr = parseFloat(shopInfo.value.startFeeStr) || 0;
  if (startFeeStr === 0) return '去结算';

  const subtotal = cartItems.value.reduce((total, item) => {
    const priceStr = parseFloat(item.listGoodsSkus?.[0]?.priceStr) || 0;
    const packPriceStr = parseFloat(item.listGoodsSkus?.[0]?.packPriceStr) || 0;
    const specAdditionalPrice = parseFloat(item.specAdditionalPrice) || 0; // 加上规格额外价格
    const quantity = parseInt(item.quantity, 10) || 0;
    return total + ((priceStr + packPriceStr + specAdditionalPrice) * quantity);
  }, 0);

  // 获取配送费
  // const deliveryFeeStr = parseFloat(shopInfo.value.deliveryFeeStr) || 0;

  // 计算总金额（商品小计 + 配送费）
  const totalAmount = subtotal;

  if (totalAmount >= startFeeStr) {
    return '去结算';
  } else {
    return `¥${startFeeStr}起送`;
  }
})

const selectedSpecText = computed(() => {
  const specs = Object.values(selectedSpecs.value)
  return specs.length > 0 ? specs.join('，') : '请选择规格'
})

// 方法
const goBack = () => {
  uni.navigateBack()
}

// 收藏店铺
const toggleCollect = async () => {
  try {
    if (isCollected.value) {
      // 取消收藏
      const res = await Fetch(`shopping/collection/cancel/${shopId.value}`, {
        method: 'delete',
      })

      if (res.data.code === 200) {
        isCollected.value = false
        uni.showToast({
          title: '已取消收藏',
          icon: 'success'
        })
      } else {
        uni.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    } else {
      // 添加收藏
      const res = await Fetch(`shopping/collection/add`, {
        method: 'post',
        data: {
          shopId: shopId.value
        }
      })

      if (res.data.code === 200) {
        isCollected.value = true
        uni.showToast({
          title: '已收藏',
          icon: 'success'
        })
      } else {
        uni.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    uni.showToast({
      title: '操作失败，请稍后再试',
      icon: 'none'
    })
  }
}

// 检查店铺是否已收藏
const shoppingCartIds = ref('') // 收藏店铺id
const checkIsCollected = async () => {
  try {
    const res = await Fetch(`shopping/collection/list`, {
      method: 'get',
    })

    if (res.data.code === 200 && res.data.rows) {
      isCollected.value = res.data.rows.some(item => item.shopId === shopId.value)
    }
  } catch (error) {
    console.error('获取收藏状态失败:', error)
  }
}

const switchTab = (tab) => {
  activeTab.value = tab
}

// 在现有代码基础上添加这些变量
const currentStickyTitle = ref('')
const stickyTitleOffset = ref(0)
const scrollIntoViewId = ref('')

// 修改现有的 handleShopScroll 方法，添加吸附标题逻辑
const handleShopScroll = (e) => {
  const scrollTop = e.detail.scrollTop;
  updateActiveCategory(scrollTop);
}

// 处理吸附标题的逻辑
const updateActiveCategory = () => {
  if (CommodityList.value.length === 0) return

  // 关键：使用 .in() 方法指定查询容器
  const query = uni.createSelectorQuery()

  // 先获取 content-right 容器的信息
  query.select('.content-right').boundingClientRect()

  // 再获取所有分类标题的位置
  CommodityList.value.forEach((_, index) => {
    query.select(`#title-${index}`).boundingClientRect()
  })

  query.exec((rects) => {
    if (!rects || rects.length < 2) return

    const containerRect = rects[0] // content-right 容器
    const titleRects = rects.slice(1) // 所有标题的位置

    let activeIndex = -1

    for (let i = 0; i < titleRects.length; i++) {
      const rect = titleRects[i]
      if (!rect) continue

      // 相对于 content-right 容器顶部的位置
      const relativeTop = rect.top - containerRect.top

      // 判断标题是否在容器视口的合适位置
      if (relativeTop <= 50 && relativeTop > -rect.height) {
        activeIndex = i
      }
    }

    if (activeIndex >= 0 && activeCategory.value !== activeIndex) {
      activeCategory.value = activeIndex
      console.log(`当前分类: ${CommodityList.value[activeIndex].title}`)
    }
  })
}

// 简化切换分类的方法
const switchCategory = (category, index) => {
  activeCategory.value = index

  // 直接滚动到锚点
  scrollIntoViewId.value = `category-anchor-${index}`

  // 延迟重置
  setTimeout(() => {
    scrollIntoViewId.value = ''
  }, 500)
}

// 显示规格
const showSpecification = (product) => {
  const SpecificationList = product.goodsSpecsList
  console.log(SpecificationList, 'SpecificationList');
  currentProduct.value = product
  currentProduct.value.priceStr = product.listGoodsSkus?.[0].marketPrice || product.listGoodsSkus?.[0].priceStr
  currentProduct.value.specifications = SpecificationList
  selectedSpecs.value = {}
  isShowSpecification.value = true
}

const closeSpecification = () => {
  isShowSpecification.value = false
  selectedSpecs.value = {}
}

const selectSpec = (specName, option) => {
  selectedSpecs.value[specName] = option.name

  // 重新计算价格：基础价格 + 所有已选规格的额外价格
  const basePrice = parseFloat(currentProduct.value.listGoodsSkus?.[0]?.marketPrice || currentProduct.value.listGoodsSkus?.[0]?.priceStr || 0)

  // 计算所有规格选项的额外价格
  let additionalPrice = 0
  currentProduct.value.specifications.forEach(spec => {
    const selectedOption = spec.list.find(opt => opt.name === selectedSpecs.value[spec.name])
    if (selectedOption && selectedOption.priceStr) {
      additionalPrice += parseFloat(selectedOption.priceStr)
    }
  })

  // 更新当前商品显示的价格
  currentProduct.value.priceStr = (basePrice + additionalPrice).toFixed(2)
}

// 规格选择后添加到购物车
const addToCart = () => {
  // 检查是否选择了所有规格
  const requiredSpecs = currentProduct.value.specifications.map(spec => spec.name)
  const selectedSpecNames = Object.keys(selectedSpecs.value)

  if (selectedSpecNames.length !== requiredSpecs.length) {
    uni.showToast({
      title: '请选择完整规格',
      icon: 'none'
    })
    return
  }

  // 构建规格详情数组（包含名称和价格）
  const specDetails = []
  let specAdditionalPrice = 0

  currentProduct.value.specifications.forEach(spec => {
    const selectedOption = spec.list.find(opt => opt.name === selectedSpecs.value[spec.name])
    if (selectedOption) {
      specDetails.push({
        optionName: spec.name,
        specsId: selectedOption.id,
        specsName: selectedOption.name,
        specsPrice: selectedOption.priceStr || 0
      })
      specAdditionalPrice += parseFloat(selectedOption.priceStr || 0)
    }
  })

  const cartItem = {
    goodsId: currentProduct.value.goodsId,
    goodsName: currentProduct.value.goodsName,
    thumbnail: currentProduct.value.thumbnail,
    categoryName: currentProduct.value.categoryName,
    categoryId: currentProduct.value.categoryId,
    specifications: Object.values(selectedSpecs.value), // 只保存规格名称用于显示
    specDetails: specDetails, // 保存完整规格信息（包含价格）
    quantity: 1,
    listGoodsSkus: currentProduct.value.listGoodsSkus,
    specAdditionalPrice: specAdditionalPrice // 保存规格额外价格
  }

  // 检查购物车中是否已存在相同商品和规格
  const existingIndex = cartItems.value.findIndex(item =>
    item.goodsId === cartItem.goodsId &&
    JSON.stringify(item.specifications) === JSON.stringify(cartItem.specifications)
  )

  if (existingIndex >= 0) {
    cartItems.value[existingIndex].quantity += 1
  } else {
    cartItems.value.push(cartItem)
  }

  closeSpecification()
  uni.showToast({
    title: '已加入购物车',
    icon: 'success'
  })
}

const toggleCart = () => {
  showCart.value = !showCart.value
}

// 修改 clearCart 方法，添加确认和防抖
let clearCartTimer = null
const clearCart = () => {
  console.log('clearCart 被调用了', new Error().stack)
  // 清除之前的定时器
  if (clearCartTimer) {
    clearTimeout(clearCartTimer)
  }

  // 添加确认提示
  uni.showModal({
    title: '确认清空',
    content: '确定要清空购物车吗？',
    success: (res) => {
      if (res.confirm) {
        cartItems.value = []
        showCart.value = false
        uni.showToast({
          title: '购物车已清空',
          icon: 'success'
        })
      }
    }
  })
}
onShareAppMessage(() => {
  return {
    title: '快跑吖-校园外卖平台',
    path: '/pages/index',
    imageUrl: '/static/imgs/logo.jpg',
  }
})
const increaseQuantity = (index) => {
  cartItems.value[index].quantity += 1
}

const decreaseQuantity = (index) => {
  if (cartItems.value[index].quantity > 1) {
    cartItems.value[index].quantity -= 1
  } else {
    cartItems.value.splice(index, 1)
    if (cartItems.value.length === 0) {
      showCart.value = false
    }
  }
}

// 添加一个标记，记录是否是从当前页面跳转出去的
const isNavigatingToPayment = ref(false)

const checkout = async () => {
  if (!canCheckout.value) {
    uni.showToast({
      title: '未达到起送金额',
      icon: 'none'
    })
    return
  }
  console.log('已选商品', cartItems.value)
  // 检查是否有必选分类，并判断购物车中是否包含必选分类的商品
  if (mandatoryChoiceObject.value && mandatoryChoiceObject.value.categoryId) {
    const hasMandatoryProduct = cartItems.value.some(item =>
      item.categoryId === mandatoryChoiceObject.value.categoryId
    )

    if (!hasMandatoryProduct) {
      // 找到必选分类在 categories 中的索引
      const mandatoryIndex = categories.value.findIndex(
        item => item.categoryId === mandatoryChoiceObject.value.categoryId
      )

      // 如果找到了分类索引，跳转到该分类
      if (mandatoryIndex !== -1) {
        // 切换到"点餐"标签页（如果当前不在点餐页）
        activeTab.value = 'order'

        // 切换到必选分类
        switchCategory(categories.value[mandatoryIndex], mandatoryIndex)
      }

      uni.showToast({
        title: `请选择必选商品：${mandatoryChoiceObject.value.categoryName || '必选分类'}`,
        icon: 'none',
        duration: 2000
      })
      return
    }
  }
  const result = await Fetch(`shopping/login/getUserInfo`)
  if (result.data.code === 200) {
    // 设置标记，表示即将跳转到支付页面
    isNavigatingToPayment.value = true

    // 这里可以跳转到支付页面
    uni.navigateTo({
      url: '/pages/Payment?cartData=' + encodeURIComponent(JSON.stringify(cartItems.value)) + '&deliveryFeeStr=' + shopInfo.value.deliveryFeeStr + '&serviceChargeStr=' + shopInfo.value.serviceChargeStr + '&extendId=' + extendId.value,
    })
  } else {
    uni.showModal({
      title: '提示',
      content: '您尚未登录，请先登录',
      showCancel: true,
      success: function (res) {
        if (res.confirm) {
          // 返回登录页
          uni.reLaunch({
            url: '/pages/login'
          });
        }
      }
    });
  }

}

// 使用节流函数来优化性能
let scrollTimer = null
const handleScroll = (e) => {
  if (scrollTimer) {
    clearTimeout(scrollTimer)
  }

  scrollTimer = setTimeout(() => {
    const scrollTopValue = e.detail.scrollTop
    scrollTop.value = scrollTopValue
    console.log('滚动位置:', scrollTopValue)

    // 当滚动距离超过170px时显示固定头部，但不阻止滚动
    showFixedHeader.value = scrollTopValue > 170

    // #ifdef MP-WEIXIN

    // #endif
  }, 16) // 约60fps的刷新率
}
// 店铺id
const shopId = ref('')
// 店铺商品分类选择id
const categoryId = ref('')
// 商品id
const goodsId = ref('')
const shopInfo = ref({})
const extendId = ref('')
onLoad((options) => {
  console.log(options)
  shopId.value = options.shopId
  categoryId.value = options.categoryId
  goodsId.value = options.goodsId
  getMerchantInfo()
  getMerchantClassification()
  checkIsCollected() // 页面加载时检查收藏状态

  // 从URL参数解析购物车数据
  if (options.cartData) {
    try {
      cartItems.value = JSON.parse(decodeURIComponent(options.cartData));
    } catch (e) {
      console.error('解析购物车数据出错:', e);
      cartItems.value = [];
    }
  }
  // if (options.extendId) {
  //   extendId.value = options.extendId
  // }
})



// 店铺详情
const getMerchantInfo = async () => {
  const res = await Fetch(`shopping/shopInfo/${shopId.value}`, {
    method: 'get',
  })
  if (res.data.code === 200) {
    const extendsJson = JSON.parse(res.data.data.extendsJson)
    res.data.data.shopExtendsJson = extendsJson
    shopInfo.value = res.data.data
  } else {
    uni.showToast({
      title: res.data.msg,
      icon: 'none',
    })
  }
}

const mandatoryChoiceObject = ref({})


// 店铺商品分类
const getMerchantClassification = async () => {
  const res = await Fetch(`shopping/goodsCategory/list`, {
    method: 'get',
    data: {
      shopId: shopId.value,
      pageSize: 100,
    }
  })
  if (res.data.code === 200) {
    // res.data.rows.unshift({
    //   categoryId: '',
    //   categoryName: '全部',
    //   icon: '',
    // })
    categories.value = JSON.parse(JSON.stringify(res.data.rows))
    categories.value.forEach(item => {
      if (item.isRequired == '1') {
        mandatoryChoiceObject.value = item
      }
    })
    sourceCategories.value = JSON.parse(JSON.stringify(res.data.rows))
    if (categoryId.value) {
      // 如果传入商品分类id，则选中该分类
      categories.value.forEach((item, index) => {
        if (item.categoryId === categoryId.value) {
          activeCategory.value = index
        }
      })

      getMerchantGoods(categoryId.value)
      return
    } else {
      getMerchantGoods('')
    }

  } else {
    uni.showToast({
      title: res.data.msg,
      icon: 'none',
    })
  }
}

const searchValue = ref('')
const handleChange = (val) => {
  searchValue.value = val.detail.value
  getMerchantGoods('', searchValue.value)
}
const CommodityList = ref([]) // 商品列表全部
// 店铺商品分类下的商品
const getMerchantGoods = async (categoryId, searchValue = '') => {
  const res = await Fetch(`shopping/goodsInfo/list`, {
    method: 'get',
    data: {
      shopId: shopId.value,
      // categoryId: categoryId,
      page: 1,
      pageSize: 1000,
      isShelves: 1,
      goodsName: searchValue,
    }
  })

  if (res.data.code === 200) {
    // categories.value[activeCategory.value].products = res.data.rows
    // res.data.rows.forEach(item => {
    //   item.goodsSpecsList = [
    //     {
    //       "name": "辣度",
    //       "specValue": "",
    //       "priceStr": 0,
    //       "parentId": 0,
    //       "sort": 1,
    //       "list": [
    //         {
    //           "name": "微辣",
    //           "priceStr": 2,
    //           "id": 1,
    //           "sort": 1
    //         },
    //         {
    //           "name": "中辣",
    //           "priceStr": 2,
    //           "id": 2,
    //           "sort": 2
    //         },
    //         {
    //           "name": "重辣",
    //           "priceStr": 4,
    //           "id": 3,
    //           "sort": 3
    //         }
    //       ]
    //     }
    //   ]
    // })
    console.log(res.data.rows, '数据查看================>')
    if (searchValue != '') {
      let list = []
      CommodityList.value = groupProductsByCategory(res.data.rows)
      console.log(groupProductsByCategory(res.data.rows), '数据查看')
      CommodityList.value.forEach(item => {
        list.push({
          categoryName: item.title,
          categoryId: item.categoryId,
        })
      })
      categories.value = list
    } else {
      categories.value = sourceCategories.value
      CommodityList.value = formatCategoriesWithAllProducts(res.data.rows)
    }
    console.log(formatCategoriesWithAllProducts(res.data.rows), 'formatCategoriesWithAllProducts');
  } else {
    uni.showToast({
      title: res.data.msg,
      icon: 'none',
    })
  }
}

// 将所有商品按分类重新组织的方法
const formatCategoriesWithAllProducts = (allProducts) => {
  // 创建一个以 categoryId 为键的商品分组对象
  const productsByCategory = {}

  // 将所有商品按分类ID分组
  allProducts.forEach(product => {
    const categoryId = product.categoryId || product.goodsCategoryId || ''
    if (!productsByCategory[categoryId]) {
      productsByCategory[categoryId] = []
    }
    productsByCategory[categoryId].push(product)
  })

  // 将分类和对应的商品组合成最终格式
  const formattedData = categories.value.map(category => {
    const categoryId = category.categoryId || ''
    return {
      title: category.categoryName,
      categoryId: categoryId,
      icon: category.icon,
      list: productsByCategory[categoryId] || []
    }
  })

  return formattedData
}

const groupProductsByCategory = (products) => {
  const groupedProducts = {};

  // 遍历商品数组
  products.forEach(product => {
    // 提取 categoryId 和 categoryName
    const { categoryId, categoryName } = product;

    // 如果 groupedProducts 中还没有这个 categoryId，初始化它
    if (!groupedProducts[categoryId]) {
      groupedProducts[categoryId] = {
        title: categoryName,
        categoryId: categoryId,
        icon: '', // 如果有 icon 字段，你可以替换这里
        list: []
      };
    }

    // 把当前商品加入对应 categoryId 的 list 中
    groupedProducts[categoryId].list.push(product);
  });

  // 返回格式化后的结果
  return Object.values(groupedProducts);
}


// 判断商品是否有规格
const hasSpecifications = (product) => {
  return Array.isArray(product.goodsSpecsList) && product.goodsSpecsList.length > 0
}

// 获取商品在购物车中的数量
const getProductQuantity = (product) => {
  // 从购物车数据中查找对应商品的数量
  const cartItem = cartItems.value.find(item => {
    // 匹配商品ID
    return item.goodsId === product.goodsId
  })
  return cartItem ? cartItem.quantity : 0
}

// 增加无规格商品数量
const increaseProductQuantity = (product) => {
  const existingIndex = cartItems.value.findIndex(item =>
    item.goodsId === product.goodsId && item.specifications.length === 0
  )

  if (existingIndex >= 0) {
    cartItems.value[existingIndex].quantity += 1
  } else {
    // 创建新的购物车项
    const cartItem = {
      goodsId: product.goodsId,
      goodsName: product.goodsName,
      thumbnail: product.thumbnail,
      categoryName: product.categoryName,
      categoryId: product.categoryId,
      specifications: [],
      quantity: 1,
      listGoodsSkus: product.listGoodsSkus
    }
    cartItems.value.push(cartItem)
  }
}

// 减少无规格商品数量
const decreaseProductQuantity = (product) => {
  const existingIndex = cartItems.value.findIndex(item =>
    item.goodsId === product.goodsId && item.specifications.length === 0
  )

  if (existingIndex >= 0) {
    if (cartItems.value[existingIndex].quantity > 1) {
      cartItems.value[existingIndex].quantity -= 1
    } else {
      cartItems.value.splice(existingIndex, 1)
    }
  }
}

// 进去商品详情页面
const handleProductClick = (product) => {
  uni.navigateTo({
    url: `/pages/ProductDetails?shopId=${shopId.value}&goodsId=${product.goodsId}&cartData=${encodeURIComponent(JSON.stringify(cartItems.value))}&shopInfo=${encodeURIComponent(JSON.stringify(shopInfo.value))}&mandatoryChoiceObject=${encodeURIComponent(JSON.stringify(mandatoryChoiceObject.value))}`,
  })
}

onMounted(() => {
  // #ifdef MP-WEIXIN
  const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  capsuleHeight.value = menuButtonInfo.height
  capsuleTop.value = menuButtonInfo.top
  console.log('胶囊按钮信息:', menuButtonInfo)
  // #endif
  // 添加购物车更新事件监听
  uni.$on('updateCart', (data) => {
    cartItems.value = data;
  });
})

onUnmounted(() => {
  // 记得移除监听，避免内存泄漏
  uni.$off('updateCart');
});
onShow(() => {
  isNavigatingToPayment.value = false
})
onUnload(() => {
  // 获取当前页面栈
  const pages = getCurrentPages()
  console.log('当前页面栈:', pages)

  // 如果是从当前页面跳转出去的（不是返回），则不执行 setCartData
  if (isNavigatingToPayment.value) {
    console.log('跳转到支付页面，不保存购物车数据')
    isNavigatingToPayment.value = false
    return
  }

  // 如果是返回上一页，则执行 setCartData
  console.log('返回上一页，保存购物车数据')
  setCartData()
})

onPageScroll((e) => {
  const scrollTopValue = e.scrollTop
  console.log(e.scrollTop, 'e');
  // 当滚动距离超过170px时显示固定头部，但不阻止滚动
  showFixedHeader.value = scrollTopValue > 140
  const query = uni.createSelectorQuery()
  query.select('.search-input').boundingClientRect((rect) => {
    if (rect) {
      console.log('搜索框位置:', rect.top, '胶囊底部位置:', capsuleTop.value + capsuleHeight.value)
      // 当搜索框顶部位置小于等于胶囊按钮底部位置时，显示固定搜索框
      isSearchFixed.value = rect.top <= (capsuleTop.value + capsuleHeight.value)
    }
  }).exec()

})



const setCartData = async () => {
  const params = {
    cartItems: cartItems.value,
    shopId: shopId.value,
    shopName: shopInfo.value.shopName,
    shopLogo: shopInfo.value.logo,
    shopType: shopInfo.value.shopType,
    totalPrice: totalPrice.value,
  }
  if (extendId.value) {
    const res = await Fetch(`shopping/extend/edit`, {
      method: 'put',
      data: {
        extendId: extendId.value,
        extendsJson: JSON.stringify(params),
      }
    })
    if (res.data.code === 200) {
      extendId.value = ''
    }
  } else {
    await Fetch(`shopping/extend/add`, {
      method: 'post',
      data: {
        extendsJson: JSON.stringify(params),
      }
    })
  }

}
</script>

<style lang="scss" scoped>
.merchant-page {
  background: #F5F5F5;

  // 固定头部样式
  .fixed-header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 88rpx;
    background: #FFFFFF;
    z-index: 999;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: flex-end;
    padding: 0 32rpx;
    box-sizing: border-box;
    pointer-events: none; // 添加这行，让固定头部不阻止滚动

    .fixed-header-content {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 10rpx;
      box-sizing: border-box;
      pointer-events: auto; // 恢复按钮的点击事件

      .fixed-back-btn {
        width: 120rpx;
        height: 60rpx;
        background: #F5F5F5;
        border-radius: 30rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        cursor: pointer; // 添加鼠标指针样式
      }

      .fixed-title {
        flex: 1;
        font-size: 32rpx;
        font-weight: bold;
        color: #191919;
        margin: 0 20rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .fixed-collect-btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        img {
          width: 40rpx;
          height: 40rpx;
        }
      }
    }
  }

  .home-page-capsule {
    position: fixed;
    left: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 100;
  }

  .home-page-banner {
    width: 750rpx;
    height: 500rpx;
    position: relative;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .merchant-logo {
    width: 702rpx;
    background: #FFFFFF;
    border-radius: 20rpx 20rpx 20rpx 20rpx;
    padding: 24rpx;
    box-sizing: border-box;
    margin: 0 auto;
    display: flex;
    align-items: self-start;
    position: relative;
    top: -100rpx;

    .logo-img {
      width: 136rpx;
      height: 136rpx;
      margin-right: 20rpx;
    }

    .merchant-logo-title {
      view {
        &:nth-child(1) {
          height: 50rpx;
          font-family: PingFang SC, PingFang SC;
          font-weight: bold;
          font-size: 36rpx;
          color: #191919;
          line-height: 50rpx;
          text-align: center;
          font-style: normal;
          text-transform: none;
          margin-bottom: 10rpx;
        }

        &:nth-child(2) {
          font-size: 22rpx;
          color: #999999;
        }
      }
    }

    .star-img {
      width: 56rpx;
      height: 56rpx;
      margin-left: auto;
      margin-top: 18rpx;
    }
  }

  .merchant-classification {
    margin-top: -70rpx;
    background: white;

    .merchant-classification-header {
      height: 118rpx;
      display: flex;
      align-items: center;
      padding: 24rpx;
      box-sizing: border-box;

      .header-item {
        height: 44rpx;
        font-weight: bold;
        font-size: 32rpx;
        color: #000000;
        line-height: 44rpx;
        text-align: center;
        font-style: normal;
        text-transform: none;
        margin-right: 74rpx;
        position: relative;

        &.active {
          &::after {
            content: '';
            position: absolute;
            bottom: -10rpx;
            left: 50%;
            transform: translateX(-50%);
            width: 40rpx;
            height: 8rpx;
            background: #F9DC40;
            border-radius: 4rpx 4rpx 4rpx 4rpx;
          }
        }
      }

      .search-container {
        position: relative;
        flex: 1;
        margin-left: 20rpx;

        .search-icon {
          position: absolute;
          left: 10rpx;
          top: 50%;
          transform: translateY(-50%);
          width: 32rpx;
          height: 32rpx;
          z-index: 1;

          img {
            width: 100%;
            height: 100%;
          }
        }

        .search-input {
          width: 100%;
          height: 60rpx;
          background: #F5F5F5;
          border-radius: 30rpx;
          padding: 0 20rpx 0 60rpx;
          box-sizing: border-box;
          font-size: 28rpx;
          color: #333;
          border: none;
          outline: none;
        }
      }
    }

    .merchant-classification-content {
      background: white;
      display: flex;

      .content-left {
        width: 162rpx;
        background: #F8F8F8;

        .content-left-item {
          height: 120rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 0rpx 20rpx 20rpx 0rpx;

          &.active {
            background: white;
            border-radius: 0rpx;
          }

          image {
            width: 24rpx;
            height: 26rpx;
          }
        }
      }

      .content-right {
        flex: 1;
        padding: 18rpx 24rpx;
        box-sizing: border-box;

        .content-right-item {

          .item-content {
            .item-content-item {
              display: flex;
              margin-bottom: 40rpx;

              image {
                width: 158rpx;
                height: 158rpx;
                border-radius: 16rpx 16rpx 16rpx 16rpx;
                margin-right: 20rpx;
              }

              .item-content-item-title {
                flex: 1;
                width: 100%;

                .one {
                  font-weight: bold;
                  font-size: 28rpx;
                  color: #000000;
                  text-transform: none;
                }

                .two {
                  height: 34rpx;
                  font-weight: 400;
                  font-size: 24rpx;
                  color: #999999;
                  line-height: 34rpx;
                  text-transform: none;
                }

                .three {
                  height: 34rpx;
                  font-weight: 400;
                  font-size: 24rpx;
                  color: #999999;
                  line-height: 34rpx;
                  text-transform: none;
                }

                .four {
                  display: flex;
                  align-items: flex-end;
                  width: 100%;

                  image {
                    width: 46rpx;
                    height: 46rpx;
                  }

                  .four-left {
                    margin-right: auto;
                    margin-bottom: 6rpx;
                    height: 44rpx;
                    font-weight: bold;
                    font-size: 32rpx;
                    color: #EA5838;
                    line-height: 44rpx;
                    text-transform: none;

                    label {
                      &:nth-child(1) {
                        height: 34rpx;
                        font-weight: bold;
                        font-size: 24rpx;
                        color: #EA5838;
                        line-height: 34rpx;
                        text-transform: none;
                      }
                    }
                  }
                }

                .four-right {
                  .four-right-copyof {
                    height: 46rpx;
                    background: #F9E149;
                    border-radius: 24rpx 24rpx 24rpx 24rpx;
                    padding: 6rpx 18rpx;
                    font-size: 24rpx;
                    font-weight: bold;
                    color: #000000;
                    line-height: 46rpx;
                  }

                  .quantity-controls {
                    display: flex;
                    align-items: center;

                    .quantity-btn {
                      width: 46rpx;
                      height: 46rpx;
                      cursor: pointer;
                    }

                    .quantity-text {
                      width: 60rpx;
                      height: 46rpx;
                      font-size: 24rpx;
                      font-weight: bold;
                      color: #000000;
                      line-height: 46rpx;
                      text-align: center;
                      margin: 0 8rpx;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }


  .Shopping-cart {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 166rpx;
    background: #FFFFFF;
    z-index: 100;
    padding: 22rpx 30rpx 64rpx 30rpx;
    box-sizing: border-box;

    .Shopping-cart-box {
      display: flex;
      align-items: center;

      .Shopping-cart-box-img {
        position: relative;

        .Shopping-cart-box-img-text {
          position: absolute;
          top: -10rpx;
          right: -10rpx;
          padding: 2rpx 14rpx;
          color: white;
          border-radius: 50%;
          background: #EB4E27;
        }
      }

      .Shopping-cart-box-text {
        .Shopping-cart-box-text-top {
          height: 36rpx;
          font-weight: bold;
          font-size: 26rpx;
          color: #EB4E36;
          margin-left: 32rpx;
          line-height: 36rpx;

          label {
            font-size: 40rpx;
          }

          margin-bottom: 10rpx;
        }

        .Shopping-cart-box-text-bottom {
          height: 28rpx;
          font-size: 20rpx;
          color: #676869;
          line-height: 28rpx;
          margin-left: 32rpx;
        }

        .start-fee-tip {
          height: 28rpx;
          font-size: 20rpx;
          color: #999999;
          line-height: 28rpx;
          margin-left: 32rpx;
          margin-top: 8rpx;
        }
      }

      .Shopping-cart-box-botton {
        width: 200rpx;
        height: 90rpx;
        background: #BCBCBD;
        border-radius: 46rpx 46rpx 46rpx 46rpx;
        font-weight: bold;
        font-size: 36rpx;
        line-height: 90rpx;
        color: #FFFFFF;
        text-align: center;
        margin-left: auto;

        &.active {
          background: #F9DC40;
          color: #000000;
        }

        // 未达到起送价时的样式
        &:not(.active) {
          background: #BCBCBD;
          color: #FFFFFF;
          cursor: not-allowed;
        }
      }
    }

    image {
      width: 74rpx;
      height: 80rpx;
    }
  }

  .Shopping-cart-wrapper {
    width: 750rpx;
    background: #F1F1F1;
    border-radius: 36rpx 36rpx 0rpx 0rpx;
    padding: 20rpx;
    box-sizing: border-box;
    position: fixed;
    bottom: 166rpx;

    .wrapper-box {
      width: 710rpx;
      background: #FFFFFF;
      border-radius: 30rpx;
      padding: 30rpx;
      box-sizing: border-box;
      margin: 0 auto;

      .wrapper-box-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 40rpx;

        .wrapper-box-header-left {
          height: 44rpx;
          font-weight: bold;
          font-size: 32rpx;
          color: #222425;
          line-height: 44rpx;
        }

        .wrapper-box-header-right {
          height: 34rpx;
          font-weight: 400;
          font-size: 24rpx;
          color: #999999;
          line-height: 34rpx;
        }
      }

      .wrapper-box-content {
        .item-content {
          .item-content-item {
            display: flex;
            margin-bottom: 40rpx;

            image {
              width: 128rpx;
              height: 132rpx;
              border-radius: 16rpx 16rpx 16rpx 16rpx;
              margin-right: 20rpx;
            }

            .item-content-item-title {
              flex: 1;
              width: 100%;

              .one {
                height: 40rpx;
                font-weight: bold;
                font-size: 28rpx;
                color: #000000;
                line-height: 40rpx;
                text-transform: none;
              }

              .two {
                height: 34rpx;
                font-weight: 400;
                font-size: 24rpx;
                color: #999999;
                line-height: 34rpx;
                text-transform: none;
              }


              .four {
                display: flex;
                align-items: flex-end;
                width: 100%;

                image {
                  width: 46rpx;
                  height: 46rpx;
                }

                .four-left {
                  margin-right: auto;
                  margin-top: 30rpx;
                  height: 44rpx;
                  font-weight: bold;
                  font-size: 32rpx;
                  color: #EA5838;
                  line-height: 44rpx;
                  text-transform: none;

                  label {
                    &:nth-child(1) {
                      height: 34rpx;
                      font-weight: bold;
                      font-size: 24rpx;
                      color: #EA5838;
                      line-height: 34rpx;
                      text-transform: none;
                    }
                  }
                }
              }

              .four-right {
                display: flex;
                align-items: center;

                .img-left,
                .img-right {
                  width: 46rpx;
                  height: 46rpx;
                  margin: 0rpx;
                }

                .img-left {
                  margin-right: 20rpx;
                }

                .img-right {
                  margin-left: 20rpx;
                }
              }
            }
          }
        }
      }
    }


  }

  .Specification-box {
    position: fixed;
    z-index: 100;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;

    .Specification-bj {
      width: 100%;
      height: 100vh;
      background: rgba(0, 0, 0, 0.5);
      position: fixed;
      z-index: 99;
      top: 0;
      left: 0;
    }

    .popup-Specification {
      width: 692rpx;
      background: #FFFFFF;
      border-radius: 36rpx 36rpx 36rpx 36rpx;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 101;

      .popup-Specification-header {
        width: 692rpx;
        height: 96rpx;
        background: #FAFAFA;
        border-radius: 36rpx 36rpx 0rpx 0rpx;
        padding: 20rpx 34rpx;
        box-sizing: border-box;
        font-weight: bold;
        font-size: 40rpx;
        color: #000000;
        line-height: 56rpx;
        text-transform: none;
      }

      .Specification-content {
        padding: 24rpx 34rpx;
        box-sizing: border-box;
        max-height: 800rpx;
        overflow-y: auto;

        .Specification-content-item {
          margin-bottom: 44rpx;

          .Specification-content-item-title {
            height: 36rpx;
            font-weight: bold;
            font-size: 26rpx;
            color: #000000;
            line-height: 36rpx;
            text-transform: none;
            margin-bottom: 16rpx;
          }

          .Specification-content-item-content {
            display: flex;
            align-items: center;
            flex-wrap: wrap;

            view {
              font-weight: 400;
              font-size: 26rpx;
              color: #37393B;
              text-transform: none;
              padding: 18rpx 26rpx;
              border-radius: 16rpx;
              background: #F6F6F7;
              box-sizing: border-box;
              margin-right: 16rpx;
              margin-bottom: 10rpx;
            }

            .active {
              background: #F9E149;
            }
          }
        }
      }

      .Specification-footer {
        background: #FAFAFA;
        border-radius: 0 0 36rpx 36rpx;

        .Specification-footer-header {
          height: 60rpx;
          font-weight: 400;
          font-size: 22rpx;
          color: #222425;
          line-height: 60rpx;
          padding-left: 32rpx;
          box-sizing: border-box;
          text-transform: none;
        }

        .Specification-footer-bottom {
          border-top: 1rpx solid #F1F1F2;
          display: flex;
          align-items: center;
          height: 92rpx;
          padding: 0 34rpx 0 32rpx;
          box-sizing: border-box;

          .left {
            height: 56rpx;
            font-weight: bold;
            font-size: 40rpx;
            color: #222425;
            line-height: 56rpx;
            text-transform: none;

            label {
              height: 32rpx;
              font-size: 22rpx;
              color: #222425;
              line-height: 32rpx;
              text-transform: none;
            }
          }

          .right {
            width: 178rpx;
            height: 56rpx;
            background: #FBE665;
            border-radius: 28rpx 28rpx 28rpx 28rpx;
            font-weight: bold;
            font-size: 22rpx;
            color: #222425;
            line-height: 56rpx;
            text-align: center;
            text-transform: none;
            margin-left: auto;
          }
        }
      }
    }
  }

  .item-content-item-wu {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin: 60rpx auto;
    text-align: center;

    image {
      width: 281rpx;
      height: 213rpx;
    }

    .text {
      margin-top: 20rpx;
      font-size: 24rpx;
      color: #999;
    }
  }

  // 优化吸附标题的样式
  .sticky-category-overlay {
    position: absolute;
    left: 162rpx; // 左侧分类栏宽度
    right: 0;
    height: 88rpx; // 增加高度，让标题更显眼
    background: linear-gradient(135deg, #FFFFFF 0%, #F8F9FA 100%); // 添加渐变背景
    border-bottom: 2rpx solid #F0F0F0;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08); // 添加阴影效果
    z-index: 100;
    transition: all 0.2s ease; // 平滑过渡

    .sticky-title-content {
      height: 100%;
      display: flex;
      align-items: center;
      padding: 0 32rpx; // 增加左右间距
      font-weight: bold;
      font-size: 36rpx; // 稍微增大字体
      color: #191919;
      box-sizing: border-box;
      position: relative;

      // 添加左侧装饰线
      &::before {
        content: '';
        position: absolute;
        left: 24rpx;
        top: 50%;
        transform: translateY(-50%);
        width: 6rpx;
        height: 36rpx;
        background: linear-gradient(180deg, #F9DC40 0%, #FBE665 100%);
        border-radius: 3rpx;
      }

      // 文字位置调整，为装饰线留空间
      padding-left: 48rpx;
    }

    // 添加hover效果（H5端）
    &:hover {
      background: linear-gradient(135deg, #F8F9FA 0%, #F0F1F2 100%);

      .sticky-title-content::before {
        background: linear-gradient(180deg, #FBE665 0%, #F9DC40 100%);
      }
    }
  }

  // 确保原有内容容器有相对定位
  .merchant-classification-content {
    position: relative;

    // 为吸附标题留出空间，避免内容被遮挡
    .content-right {
      padding-top: 0; // 确保顶部对齐
    }
  }


}

.sticky-header {
  position: sticky;
  top: 0;
  height: 50px; // 固定标题高度
  display: flex;
  align-items: center;
  font-weight: bold;
  font-size: 32rpx;
  color: #000000;
  background: linear-gradient(135deg, #FFFFFF 0%, #FAFBFC 100%); // 渐变背景
  padding: 0 24rpx;
  margin-bottom: 30rpx;
  border-radius: 12rpx; // 圆角
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04); // 轻微阴影
  border-left: 6rpx solid #F9DC40; // 左侧黄色装饰条

  div {
    font-size: 34rpx; // 稍微增大字体
    font-weight: bold;
    color: #191919;
    position: relative;

    // 添加装饰图标
    &::before {
      content: '●';
      color: #F9DC40;
      font-size: 16rpx;
      margin-right: 12rpx;
      vertical-align: middle;
    }
  }

  label {
    height: 34rpx;
    font-weight: 400;
    font-size: 24rpx;
    color: #999999;
    line-height: 34rpx;
    margin-left: 10rpx;
    background: rgba(249, 220, 64, 0.1);
    padding: 4rpx 12rpx;
    border-radius: 12rpx;
  }

  // 添加底部装饰线
  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 30rpx;
    right: 30rpx;
    height: 2rpx;
    background: linear-gradient(90deg, #F9DC40 0%, transparent 100%);
  }

  // 悬停效果（H5端）
  &:hover {
    background: linear-gradient(135deg, #FAFBFC 0%, #F5F6F7 100%);
    transform: translateY(-2rpx);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
    transition: all 0.2s ease;
  }
}

.last-section {
  padding-bottom: 300rpx;
}
</style>
